﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using AutoMapper;
using Dogshow.Model;
using DogshowRepository;
using System.Linq;

namespace Dogshow.Linq2SQLRepository
{
    public class MestaRepository : RepositoryBase, IMestaRepository
    {
        public int Sacuvaj(Mesto entity)
        {
            using (var ctx = new DogshowModel())
            {
                Mesta mesta;
                if (entity.Id == 0)
                {
                    mesta = ModelMapper.Map(entity);
                    ctx.Mestas.InsertOnSubmit(mesta);
                    ctx.SubmitChanges();
                }
                else
                {
                    mesta = ctx.Mestas.Single(x => x.Id == entity.Id);
                    ModelMapper.Map(entity, mesta);
                    ctx.Submit();
                }
                return mesta.Id;    
            }
        }

        public IEnumerable<Mesto> VratiSve()
        {
            using (var model = new DogshowModel())
            {
                return model.Mestas.Select(ModelMapper.Map).ToArray();    
            }
        }

        public Mesto VratiPoId(int id)
        {
            using (var model = new DogshowModel())
            {
                var m = model.Mestas.SingleOrDefault(x => x.Id == id);
                if (m == null) return null;
                return ModelMapper.Map(m); 
            }
        }

        public IEnumerable<Mesto> FiltrirajPoNazivu(string deoNaziva, int begin, int take)
        {
            using (var model = new DogshowModel())
            {
                IQueryable<Mesta> mesta = model.Mestas;
                if (!String.IsNullOrEmpty(deoNaziva))
                {
                    mesta = mesta.Where(x => x.Naziv.Contains(deoNaziva));
                }
                return mesta.Skip(begin).Take(take).Select(ModelMapper.Map).ToArray(); 
            }
        }

        public IEnumerable<Mesto> FiltrirajPoNazivu(string deoNaziva)
        {
            return FiltrirajPoNazivu(deoNaziva, 0, 1);
        }

        public Mesto VratiPoPostanskomBroju(string postanskiBroj)
        {
            using (var model = new DogshowModel())
            {
                return model.Mestas.Where(x => x.PostanskiBroj == postanskiBroj).Select(ModelMapper.Map).FirstOrDefault();
            }
        }
    }
}